package cn.iocoder.yudao.module.dbit.service.jobinfo;

import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.QueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.dbit.dal.dataobject.jobinfo.JobCollectionInfoDO;
import cn.iocoder.yudao.module.dbit.dal.dataobject.jobinfo.StudentCheckJobInfoDO;
import cn.iocoder.yudao.module.dbit.dal.dataobject.stumst.StuMstDO;
import cn.iocoder.yudao.module.dbit.dal.mysql.jobinfo.JobCollectionInfoMapper;
import cn.iocoder.yudao.module.dbit.dal.mysql.jobinfo.StudentCheckJobInfoMapper;
import cn.iocoder.yudao.module.dbit.dal.mysql.stumst.StuMstMapper;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.dbit.controller.admin.jobinfo.vo.*;
import cn.iocoder.yudao.module.dbit.dal.dataobject.jobinfo.JobInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.dbit.dal.mysql.jobinfo.JobInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.dbit.enums.ErrorCodeConstants.*;

/**
 * 企业职位信息 Service 实现类
 *
 * @author DaBen
 */
@Service
@Validated
@Slf4j
public class StudentCheckJobInfoServiceImpl implements StudentCheckJobInfoService {


    @Autowired
    private StudentCheckJobInfoMapper jobInfoMapper;
    @Resource
    private StuMstMapper stuMstMapper;
    @Resource
    private AdminUserMapper adminUserMapper;

    @Resource
    private JobCollectionInfoMapper jobCollectionInfoMapper;


    @Override
    @TenantIgnore
    public StudentCheckJobInfoDO getJobInfo(Integer id) {
        StudentCheckJobInfoDO studentCheckJobInfoDO = jobInfoMapper.selectByJobId(id);
        QueryWrapper<JobCollectionInfoDO> queryWrapper = new QueryWrapper<>();
        //获取当前登录人id
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        Integer uid = userId != null ? userId.intValue() : 0;
        //查询职位是否被收藏了
        queryWrapper.eq("job_id",id).eq("user_id",uid);
        JobCollectionInfoDO jobCollectionInfoDO = jobCollectionInfoMapper.selectOne(queryWrapper);
        List<Integer> cityIds = Arrays.stream(studentCheckJobInfoDO.getJobCity().split(";"))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        StringBuilder cityNames = new StringBuilder();
        cityIds.forEach(cityId -> {
            cityNames.append(AreaUtils.getArea(cityId).getName()).append(";");
        });
        studentCheckJobInfoDO.setJobCity(cityNames.toString());
        studentCheckJobInfoDO.setCollectionStatus(jobCollectionInfoDO != null);
        return studentCheckJobInfoDO;
    }


    @Override
    @TenantIgnore
    public PageResult<StudentCheckJobInfoDO> getJobInfoPage(JobInfoPageReqVO pageReqVO) {
        IPage<StudentCheckJobInfoDO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());

        IPage<StudentCheckJobInfoDO> allJob = jobInfoMapper.selectAllJob(page, pageReqVO);
        List<StudentCheckJobInfoDO> result = new ArrayList<>();
        for (StudentCheckJobInfoDO jobInfo : allJob.getRecords()) {
            StudentCheckJobInfoDO jobInfoRespVO = BeanUtils.toBean(jobInfo, StudentCheckJobInfoDO.class);
            List<Integer> cityIds = Arrays.stream(jobInfo.getJobCity().split(";"))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            ArrayList<String> cityNames = new ArrayList<>();
            cityIds.forEach(id -> {
                cityNames.add(AreaUtils.getArea(id).getName());
            });
            String cityCollect = String.join(";", cityNames);
            jobInfoRespVO.setJobCity(cityCollect);
            result.add(jobInfoRespVO);
        }
        // 创建一个新的PageResult<JobInfoRespVO>对象，将result作为新的list
        return new PageResult<>(result, allJob.getTotal());
    }

    @Override
    @TenantIgnore
    public List<StudentRecommendJobInfoVO> recommendJobInfo(Integer userId) {
        // 获取学生用户的求职期望
        StuMstDO student = stuMstMapper.selectById(userId);
        if (student == null || !StringUtils.hasText(student.getJobTitleId())) {
            // 学生没有求职意向,随机显示5条职位信息
//            List<JobInfoDO> randJobInfo = jobInfoMapper.randJobInfo();
            return null;
        }
        // 需要推荐岗位
        // 获取到该学生的求职期望
        String[] jobTitleIds = student.getJobTitleId().split(";");
        List<String> list = Arrays.asList(jobTitleIds);
        List<JobInfoDO> recommendJobInfo = jobInfoMapper.recommendJobInfo(list);
        List<StudentRecommendJobInfoVO> result = changeJobInfo(recommendJobInfo);
        return result;
    }

    @Override
    @TenantIgnore
    public List<StudentRecommendJobInfoVO> latestJobInfo() {
        List<JobInfoDO> latestJobInfoList = jobInfoMapper.latestJobInfo();
        List<StudentRecommendJobInfoVO> result = changeJobInfo(latestJobInfoList);
        return result;
    }

    /**
     * 将职位信息转换为前端需要的格式
     *
     * @param jobInfoList
     * @return
     */
    @TenantIgnore
    private List<StudentRecommendJobInfoVO> changeJobInfo(List<JobInfoDO> jobInfoList) {
        List<StudentRecommendJobInfoVO> result = new ArrayList<>();
        jobInfoList.forEach(jobInfo -> {
            StudentRecommendJobInfoVO vo = BeanUtils.toBean(jobInfo, StudentRecommendJobInfoVO.class);
            List<Integer> cityIds = Arrays.stream(jobInfo.getJobCity().split(";"))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            ArrayList<String> cityNames = new ArrayList<>();
            cityIds.forEach(id -> {
                cityNames.add(AreaUtils.getArea(id).getName());
            });
            String cityCollect = String.join(";", cityNames);
            vo.setJobCity(cityCollect);
            // 获取该职位的创建公司
            String creator = jobInfo.getCreator();
            // 获取对应公司的头像+名称
            AdminUserDO adminUserDO = adminUserMapper.selectById(creator);
            vo.setAvatar(adminUserDO.getAvatar());
            vo.setNickname(adminUserDO.getNickname());
            result.add(vo);
        });
        return result;
    }

}